<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <label class="el-form-item-label">名称</label>
        <el-input
          v-model="query.name"
          clearable
          placeholder="名称"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <!-- 搜索 -->
        <label class="el-form-item-label">进程id</label>
        <el-input
          v-model="query.pid"
          clearable
          placeholder="进程id"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">状态</label>
        <el-input
          v-model="query.status"
          clearable
          placeholder="状态"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />

        <label class="el-form-item-label">目标状态</label>
        <el-input
          v-model="query.targetStatus"
          clearable
          placeholder="目标状态"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="名称">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>

          <el-form-item label="命令">
            <el-input v-model="form.command" :rows="3" type="textarea" style="width: 370px;" />
          </el-form-item>

          <el-form-item label="状态">
            <el-select v-model="form.status" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.process_status"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="目标状态">
            <el-select v-model="form.targetStatus" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.process_status"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="描述">
            <el-input v-model="form.description" :rows="3" type="textarea" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="command" label="命令" />
        <el-table-column prop="pid" label="进程id" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ dict.label.process_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkPer(['admin','processor:edit','processor:del'])"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
        <el-table-column label="管理" width="auto" align="center">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="停止" placement="top-start">
              <el-button
                v-if="scope.row.status==='RUNNING'"
                type="warning"
                size="mini"
                icon="el-icon-video-pause"
                @click="destroy(scope.row)"
              />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="强制停止" placement="top-start">
              <el-button
                v-if="scope.row.status==='RUNNING'"
                type="danger"
                size="mini"
                icon="el-icon-video-pause"
                @click="destroy(scope.row)"
              />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="启动" placement="top-start">
              <el-button
                v-if="scope.row.status!=='RUNNING'"
                type="danger"
                size="mini"
                icon="el-icon-video-play"
                @click="exec(scope.row)"
              />
            </el-tooltip>

            <el-tooltip class="item" effect="dark" content="日志" placement="top-start">
              <el-button
                v-if="scope.row.status==='RUNNING'"
                type="primary"
                size="mini"
                icon="el-icon-chat-dot-round"
                @click="showLogFunc(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
      <el-drawer
        title="日志"
        :visible.sync="showLog"
      >
        <ul v-for="item in logList" :key="item.id">{{ item.log }}</ul>
      </el-drawer>
    </div>
  </div>

</template>

<script>
import crudProcessor from '@/api/system/processor'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation.vue'
import crudOperation from '@crud/CRUD.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import pagination from '@crud/Pagination.vue'

const defaultForm = {
  id: null,
  command: null,
  pid: null,
  status: null,
  name: null,
  targetStatus: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  description: null
}
export default {
  name: 'Processor',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['process_status'],
  cruds() {
    return CRUD({
      title: 'processor',
      url: 'api/processor',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudProcessor }
    })
  },

  data() {
    return {
      permission: {
        add: ['admin', 'processor:add'],
        edit: ['admin', 'processor:edit'],
        del: ['admin', 'processor:del']
      },
      rules: {
        id: [
          { required: true, message: '主键不能为空', trigger: 'blur' }
        ]
      },
      showLog: false,
      instance: null,
      locals: {
        // 传递初始值
        name: 'Your Name'
      },
      logStr: '',
      logList: [],
      queryTypeOptions: [
        { key: 'pid', display_name: '进程id' },
        { key: 'status', display_name: '状态' },
        { key: 'name', display_name: '名称' },
        { key: 'targetStatus', display_name: '目标状态' }
      ]
    }
  },
  created() {
    this.initStatusWebSocket()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    exec(data) {
      crudProcessor.exec(data).then(res => {
        this.$message.success('请求成功')
      },
      () => {
        this.$message.success('请求失败')
      }
      )
    },
    destroy(data) {
      crudProcessor.destroy(data).then(res => {
        this.$message.success('请求成功')
      },
      () => {
        this.$message.success('请求失败')
      }
      )
    },
    destroyForcibly(data) {
      crudProcessor.destroyForcibly(data).then(res => {
        this.$message.success('请求成功')
      },
      () => {
        this.$message.success('请求失败')
      }
      )
    },
    initStatusWebSocket() {
      const wsUri = (process.env.VUE_APP_WS_API === '/' ? '/' : (process.env.VUE_APP_WS_API + '/')) + 'ws/processor'
      this.statusWebsock = new WebSocket(wsUri)
      this.statusWebsock.onerror = this.statusWSOnError
      this.statusWebsock.onmessage = this.statusWSOnMessage
    },
    statusWSOnError(e) {
      this.$notify({
        title: 'Status WebSocket连接发生错误',
        type: 'error',
        duration: 0
      })
    },
    statusWSOnMessage(e) {
      const data = JSON.parse(e.data)
      if (data.type === 'STATUS') {
        const id = data.msg.id
        const status = data.msg.status
        const pid = data.msg.pid
        console.log(this.crud.data)
        for (let i = 0; i < this.crud.data.length; i++) {
          if (this.crud.data[i].id === id) {
            this.crud.data[i].status = status
            this.crud.data[i].pid = pid
          }
        }
      }
    },
    initLogWebSocket(data) {
      const wsUri = (process.env.VUE_APP_WS_API === '/' ? '/' : (process.env.VUE_APP_WS_API + '/')) + 'ws/processor/' + data.id
      this.logWebsock = new WebSocket(wsUri)
      this.logWebsock.onerror = this.logWSOnError
      this.logWebsock.onmessage = this.logWSOnMessage
    },
    logWSOnError(e) {
      this.$notify({
        title: 'Log WebSocket连接发生错误',
        type: 'error',
        duration: 0
      })
    },
    logWSOnMessage(e) {
      const data = JSON.parse(e.data)
      if (data.type === 'LOG') {
        this.logList.push({ id: data.id, level: data.level, log: data.msg })
        this.logList = this.logList.reverse().slice(0, 100).reverse()
      }
      console.log(this.logList)
    },
    showLogFunc(data) {
      this.initLogWebSocket(data)
      this.showLog = true
    }
  }
}
</script>
